package cc.ufinity.networkdiagnose.widget;

import java.util.List;
import java.util.Map;

import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.TelManager;
import cc.ufinity.networkdiagnose.manager.WlanManager;
import cc.ufinity.networkdiagnose.view.R;
import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class RssiWidget extends GeneralTestWidget {

	private Handler handler;
	private Activity ctx;
	private TelManager tm;
	private WlanManager wlanManager;
	private ListView wifiView;
	private LinearLayout phoneLayout;
	private Button btnBack;

	public RssiWidget(Activity context) {
		super(context);
		inflate(context, R.layout.rssi_widget, this);
		this.ctx = context;
		wifiView = (ListView) this.findViewById(R.id.wifiListView);
		phoneLayout = (LinearLayout) this.findViewById(R.id.myPhoneInfo);
		btnBack = (Button) this.findViewById(R.id.rssi_btnback);
		wlanManager = new WlanManager(ctx);
		btnBack.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				back(ctx);
			}
		});
		handler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case MessageWhat.TEL_STATE_SUCCESS:
					updateTel();
					break;
				case MessageWhat.WIFI_RECEIVE_LIST:
					updateWifi();
					dismissMessageDialog();
					break;
				}
			}
		};

		tm = new TelManager(ctx);
		tm.setHandler(handler);
		wlanManager.setHandler(handler);
		start();

	}

	private void start() {
		this.showMessageDialog(ctx, "正在进行RSSI测试...");
		wlanManager.startScan();
	}

	private void updateTel() {
		phoneLayout.removeAllViews();
		TextView tv = new TextView(ctx);
		LayoutParams lp = new LayoutParams(
				LinearLayout.LayoutParams.FILL_PARENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);
		lp.setMargins(15, 5, 5, 5);
		tv.setLayoutParams(lp);
		tv.setText("网络类型:" + tm.getNetworkType());
		phoneLayout.addView(tv);
		tv = new TextView(ctx);
		tv.setLayoutParams(lp);
		tv.setText(tm.getStrSignalStrength());
		phoneLayout.addView(tv);

	}

	private void updateWifi() {
		List<Map<String, Object>> data = wlanManager.getWifiList();
		SimpleAdapter adapter = new SimpleAdapter(ctx, data,
				R.layout.wifi_list_widget, new String[] { "ssid", "mac", "img",
						"level" }, new int[] { R.id.wifi_ssid, R.id.wifi_mac,
						R.id.wifi_img, R.id.wifi_level });
		wifiView.setAdapter(adapter);
	}

}
